package com.lb.shopguide.ui.fragment.guide.goods;

import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.RelativeSizeSpan;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.lb.baselib.http.ResponseCode;
import com.lb.baselib.http.SimpleLbObserver;
import com.lb.baselib.http.bean.BaseResponse;
import com.lb.shopguide.R;
import com.lb.shopguide.base.BaseCommonFragment;
import com.lb.shopguide.config.AppConfigManager;
import com.lb.shopguide.constants.AppConstant;
import com.lb.shopguide.entity.goods.GoodsDetailBean;
import com.lb.shopguide.entity.goods.GoodsPicBean;
import com.lb.shopguide.entity.goods.SkuBean;
import com.lb.shopguide.http.method.ApiMethodGuide;
import com.lb.baselib.http.SimpleObserverOnNextListener;
import com.lb.shopguide.ui.view.LbSkuDisplayLayout;
import com.lb.shopguide.util.json.JsonUtil;
import com.lb.shopguide.util.lb.BizGoodsUtil;
import com.lb.shopguide.util.pic.GlideImageLoader;
import com.trello.rxlifecycle2.android.FragmentEvent;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by kang on 2017/6/14.
 */

public class FragmentGoodsDetail extends BaseCommonFragment {
    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.tv_goods_name)
    TextView tvGoodsName;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.tv_distribute_mode)
    TextView tvDistributeMode;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.layout_sku)
    LbSkuDisplayLayout layoutSku;
    @BindView(R.id.layout_publish_goods)
    RelativeLayout layoutPublishGoods;

    //    private GoodsInListBean mGoodsInListBean;
    private String productCode;
    private GoodsDetailBean mGoodsDetailBean;

    private int mode;



    public static FragmentGoodsDetail newInstance(String productCode, int mode) {
        FragmentGoodsDetail fragmentGoodsDetail = new FragmentGoodsDetail();
        Bundle bundle = new Bundle();
        bundle.putString(AppConstant.PRODUCT_CODE, productCode);
        bundle.putInt(AppConstant.GOODS_DETAIL_MODE, mode);
        fragmentGoodsDetail.setArguments(bundle);
        return fragmentGoodsDetail;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_goods_detail;
    }

    @Override
    public void initData() {
        Bundle bundle = getArguments();
        if (bundle.containsKey(AppConstant.PRODUCT_CODE)) {
            productCode = bundle.getString(AppConstant.PRODUCT_CODE);
        }
        if (bundle.containsKey(AppConstant.GOODS_DETAIL_MODE)) {
            mode = bundle.getInt(AppConstant.GOODS_DETAIL_MODE);
        }
        initRequest();
    }

    @Override
    public void initView() {
        banner.setImageLoader(new GlideImageLoader());
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        banner.setBannerAnimation(Transformer.DepthPage);
        //设置自动轮播，默认为true
        banner.isAutoPlay(true);
        //设置轮播时间
        banner.setDelayTime(5000);

    }

    @Override
    public void finishRefresh() {

    }

    @Override
    public void sessionOutOfDate() {
        _mActivity.finish();
    }

    @Override
    public void requestError(String error) {
        ToastUtils.showShort(error);
    }

    @Override
    public String getPageTag() {
        return FragmentGoodsDetail.class.getName();
    }

    private void bindData() {
        tvGoodsName.setText(mGoodsDetailBean.getProductName());
        if (!TextUtils.isEmpty(mGoodsDetailBean.getPriceRange())) {
            tvPrice.setText(mGoodsDetailBean.getPriceRange());

            SpannableString mSp2 = new SpannableString(tvPrice.getText().toString());
            mSp2.setSpan(new RelativeSizeSpan(0.5f), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);  //0.5f表示
            tvPrice.setText(mSp2);
        }

        if (mGoodsDetailBean.getDistributeMode() == AppConstant.DISTRIBUTE_MODE_PICK) {
            tvDistributeMode.setVisibility(View.VISIBLE);
            tvDistributeMode.setText("自提");
        } else if (mGoodsDetailBean.getDistributeMode() == AppConstant.DISTRIBUTE_MODE_EXPRESS) {
            tvDistributeMode.setVisibility(View.VISIBLE);
            tvDistributeMode.setText("快递");
        } else {
            tvDistributeMode.setVisibility(View.GONE);
        }

        bindBanner();

        layoutSku.setData(BizGoodsUtil.getSizeAndColorInDetail((ArrayList<SkuBean>) mGoodsDetailBean.getProductSkuList()));
    }

    private void bindBanner() {
        List<String> urls = new ArrayList<>();
        List<GoodsPicBean> list = mGoodsDetailBean.getProductPicList();
        for (int i = 0; i < list.size(); i++) {
            urls.add(list.get(i).getProductPicUrl());
        }

        banner.setImages(urls);
        banner.start();
    }

    private void initRequest() {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    mGoodsDetailBean = (GoodsDetailBean) JsonUtil.getObject(response.getReturnContent(), GoodsDetailBean.class);
                    bindData();
                }
            }
        };
        ApiMethodGuide.getGoodsDetail(new SimpleLbObserver(listener,otherListener),productCode,this, FragmentEvent.DESTROY_VIEW);
    }

    public void onRefresh() {
        initRequest();
    }

    @Override
    public boolean onBackPressedSupport() {
        if (mode == AppConstant.GOODS_DETAIL_NORMAL) {
            pop();
        } else if (mode == AppConstant.GOODS_DETAIL_FROM_CHAT) {
            _mActivity.finish();
        }
        return true;
    }

    @OnClick(R.id.layout_publish_goods)
    void publishGoods() {
        if (mGoodsDetailBean != null) {
            if (AppConfigManager.getAppconfigManager(mContext).getDevMode() == AppConstant.KEY_RUN_MODE_FORMAL) {
                start(FragmentPublishGoods.newInstance("https://singlepage.storeer.com/v2/editGoods_n?" + "staffCode=" + mUserConfigManager.getUserId()
                        + "&id=" + mGoodsDetailBean.getId() + "&token=" + mUserConfigManager.getUserToken() + "&type=android", AppConstant.PUBLISH_TYPE_EDIT));
            } else {
                start(FragmentPublishGoods.newInstance("http://192.168.1.102:8088/v2/editGoods_n?" + "staffCode=" + mUserConfigManager.getUserId()
                        + "&id=" + mGoodsDetailBean.getId() + "&token=" + mUserConfigManager.getUserToken() + "&type=android", AppConstant.PUBLISH_TYPE_EDIT));
            }
//                    start(FragmentPublishGoods.newInstance("http://192.168.1.49:8088/v2/editGoods_n?" + "staffCode=" + mUserConfigManager.getUserId()
//                            + "&id=" + mGoodsDetailBean.getId() + "&token=" + mUserConfigManager.getUserToken() + "&type=android", AppConstant.PUBLISH_TYPE_EDIT));
        } else {
            ToastUtils.showShort("数据未加载完全，请退出重试");
        }
    }

    @OnClick(R.id.iv_back)
    void back() {
        if (mode == AppConstant.GOODS_DETAIL_NORMAL) {
            pop();
        } else if (mode == AppConstant.GOODS_DETAIL_FROM_CHAT) {
            _mActivity.finish();
        }
    }

}
